import { request } from "https";

let robotUrl = `https://open.feishu.cn/open-apis/bot/v2/hook/xxxxxxxxxxxxxxxxx`;

/**
 * 消息模版 post
 * @param packageName     包名
 * @param version         版本
 * @param who             发布人
 * @param changeLog       变更日志
 * @param detailUrl       详情地址
 * @returns {{msg_type: string, content: {post: {zh_cn: {title: string, content: [{tag: string, text: string},{tag: string, text},{tag: string, text: string},{tag: string, text: string, href: string}][]}}}}}
 */
export const getMsgByPost = ({
  packageName,
  version,
  who,
  changeLog,
  detailUrl,
}) => {
  if (!detailUrl) {
    detailUrl = `https://www.npmjs.com/package/${packageName}`;
    if (version.includes("-")) {
      detailUrl += `/v/${version}`;
    }
  }
  return {
    msg_type: "post",
    content: {
      post: {
        zh_cn: {
          title: `${packageName}发布${version}`,
          content: [
            [
              {
                tag: "text",
                text: `发布人：${who} \n`,
              },
              {
                tag: "text",
                text: `${changeLog} \n`,
              },
              {
                tag: "a",
                text: "🔎 查看更新详情",
                href: detailUrl,
              },
            ],
          ],
        },
      },
    },
  };
};

/**
 * 消息模版 interactive
 * @param packageName     包名
 * @param version         版本
 * @param who             发布人
 * @param changeLog       变更日志
 * @param detailUrl       详情地址
 * @returns {{msg_type: string, card: {elements: [{tag: string},{tag: string, text: {tag: string, content: string}},{tag: string, text: {tag: string, content}},{tag: string, text: {tag: string, content: string}}], header: {title: {tag: string, content: string}}}}}
 */
export const getMsgByCard = ({
  packageName,
  version,
  who,
  changeLog,
  detailUrl,
}) => {
  if (!detailUrl) {
    detailUrl = `https://www.npmjs.com/package/${packageName}`;
    if (version.includes("-") > -1) {
      detailUrl += `/v/${version}`;
    }
  }
  return {
    msg_type: "interactive",
    card: {
      header: {
        title: {
          content: `${packageName}发布${version}`,
          tag: "plain_text",
        },
      },
      elements: [
        {
          tag: "hr",
        },
        {
          tag: "div",
          text: {
            content: `发布人：${who} \n`,
            tag: "lark_md",
          },
        },
        {
          tag: "div",
          text: {
            content: `${changeLog} \n`,
            tag: "lark_md",
          },
        },
        {
          tag: "div",
          text: {
            content: `[🔎 查看更新详情](${detailUrl})`,
            tag: "lark_md",
          },
        },
      ],
    },
  };
};

/**
 * 消息模版 text
 * @param text            消息内容
 * @returns {{msg_type: string, content: {text: string}}}
 */
export const getMsgByText = ({ text = "request example" }) => {
  return { msg_type: "text", content: { text } };
};

/**
 * 推送给机器人
 * @param url             推送地址
 * @param data            推送数据
 */
export const postToRobot = ({ url = robotUrl, data }) => {
  return new Promise((resolve, reject) => {
    const postData = JSON.stringify(data);

    const options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(postData),
      },
    };

    const req = request(url, options, (res) => {
      // console.log(`STATUS: ${res.statusCode}`);
      // console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
      res.setEncoding("utf8");
      res.on("data", (chunk) => {
        // console.log(`BODY: ${chunk}`);
      });
      res.on("end", () => {
        resolve();
      });
    });

    req.on("error", (err) => {
      reject(err);
    });

    // Write data to request body
    req.write(postData);
    req.end();
  });
};
